package com.kim.androidbase.log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import com.kim.androidbase.tools.DateAndValueOfUtils;

/**
 * Title: 日志管理类 Description: XXXX (简单对此类或接口的名字进行描述) Copyright: Copyright (c)
 * 2008 Company:深圳彩讯科技有限公司
 * 
 * @author X
 * @version 1.0
 */
public class LogUtil {

	private static String LOG_PATH = "sdcard/$packageName$/logs/";
	private static final String[] LEVEL = new String[] { "V", "D", "I", "W",
			"E" };

	private static boolean LOG_PATH_INIT = false;

	/**
	 * 设置日志路径
	 * 
	 * @param packageName
	 */
	public static void setLogPath(String packageName) {
		LOG_PATH = LOG_PATH.replace("$packageName$", packageName);
		LOG_PATH_INIT = true;
	}

	public static void v(String tag, String log) {
		writeLog(0, tag, log);
	}

	public static void d(String tag, String log) {
		writeLog(1, tag, log);
	}

	public static void i(String tag, String log) {
		writeLog(2, tag, log);
	}

	public static void w(String tag, String log) {
		writeLog(3, tag, log);
	}

	public static void e(String tag, String log) {
		writeLog(4, tag, log);
	}

	private static void writeLog(int level, String tag, String log) {

		if (!LOG_PATH_INIT) {
			throw new RuntimeException(
					"Log path not init! please invok func :: setLogPath.");
		}

		Date logDate = new Date();
		String logStr = String.format("[%s] %s %s : %s \n", DateAndValueOfUtils
				.DateToString(DateAndValueOfUtils.yyyy_MM_dd_HH_mm_ss, logDate,
						""), LEVEL[level], tag, log);

		File logFile = null;
		FileOutputStream fileOutputStream = null;
		try {
			logFile = new File(LOG_PATH
					+ DateAndValueOfUtils.DateToString(
							DateAndValueOfUtils.yyyy_MM_dd, logDate, "")
					+ ".log");
			if (!logFile.exists()) {
				logFile.getParentFile().mkdirs();
				logFile.createNewFile();
			}
			byte[] buffer = logStr.getBytes("utf-8");
			fileOutputStream = new FileOutputStream(logFile, true);
			fileOutputStream.write(buffer, 0, buffer.length);
			fileOutputStream.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fileOutputStream != null) {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}
}
